<template>
  <a-card :bordered="false" class="proCard">
    <BasicTable
      leftTitle="表格列表"
      leftTitleTooltip="这是一个提示"
      :columns="columns"
      :request="loadDataTable"
      row-key="id"
      ref="tableRef"
      :actionColumn="actionColumn"
      @edit-end="editEnd"
      @edit-change="onEditChange"
    >
      <template #toolbar>
        <a-button type="primary" @click="reloadTable">刷新数据</a-button>
      </template>
    </BasicTable>
  </a-card>
</template>

<script lang="ts" setup>
  import { reactive, ref, h } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { getTableList } from '@/api/table/list';
  import { columns } from './rowColumns';
  import { renderIcon } from '@/utils';
  import { FormOutlined } from '@vicons/antd';

  const tableRef = ref();
  const currentEditKeyRef = ref('');
  const params = reactive({
    pageSize: 5,
    name: 'xiaoMa',
  });

  const actionColumn = reactive({
    width: 160,
    title: '操作',
    key: 'action',
    fixed: 'right',
    align: 'center',
    render({ record, rowIndex }) {
      return h(TableAction, {
        style: 'button',
        actions: createActions(record, rowIndex),
      });
    },
  });

  function handleEdit(record) {
    console.log(record);
    currentEditKeyRef.value = record.key || record.dataIndex;
    record.onEdit?.(true);
  }

  function handleCancel(record) {
    currentEditKeyRef.value = '';
    record.onEdit?.(false, false);
  }

  function onEditChange({ column, value, record }) {
    console.log(column, value, record);
  }

  async function handleSave(record) {
    const pass = await record.onEdit?.(false, true);
    if (pass) {
      currentEditKeyRef.value = '';
    }
  }

  function createActions(record, rowIndex) {
    if (!record.editable) {
      return [
        {
          label: '编辑',
          icon: renderIcon(FormOutlined),
          onClick: handleEdit.bind(null, record, rowIndex),
        },
      ];
    } else {
      return [
        {
          label: '保存',
          type: 'primary',
          onClick: handleSave.bind(null, record, rowIndex),
        },
        {
          label: '取消',
          onClick: handleCancel.bind(null, record, rowIndex),
        },
      ];
    }
  }

  const loadDataTable = async (res) => {
    return await getTableList({ ...params, ...res });
  };

  function reloadTable() {
    console.log(tableRef.value);
    tableRef.value.reload();
  }

  function editEnd({ record, index, key, value }) {
    console.log(record);
    console.log(index);
    console.log(key);
    console.log(value);
  }
</script>

<style lang="less" scoped></style>
